iT邦幫忙

2026 iThome 鐵人賽

DAY 13
0

不知各位還記的在介紹unknown時,我在舉例中提到的typeof嗎?在TypeScript中,我們一步一步用條件判斷縮小型別的範圍,這是我們今天要介紹的型別收窄,而typeof也是型別收窄的一類喔!


1. typeof

typeof是型別收窄中最常見的類型,常用在原始型別(如:stringboolean...)的判斷中。

//typeof範例:
function printID(id: string | number) {
  if (typeof id === "string") {
    console.log(id.toUpperCase()); 
    //此時TS就能確認id這個參數的型別是string,進而使用方法
  } else {
    console.log(id * 10);
  } //因為聯合型別只可能是string或number,如果不是字串的話,型別只能是數字了
}

//typeof也能使用!==的寫法:
function printID_2(id: string | number) {
  if (typeof id !== "number") {
    console.log(id.toUpperCase()); 
  } else {
    console.log(id * 10);
  }
}

注意:typeof判斷的是JavaScript執行時取得的型別名稱,因此右邊通常會寫成 "string""number""boolean"字串

2. instanceof

如果我們要判斷的值是否為某個class的實例,可以使用instanceof來進行型別收窄。

//instanceof範例:
//先創建兩個class實例
class Student {
  learning() { console.log("上課"); }
}
class Employee {
  working() { console.log("上班"); }
}

function move(human: Student | Employee) {
  if (human instanceof Student) {
    human.learning();
  } else {
    human.working();
  }
}

簡單來說,typeof常用來判斷原始型別,而instanceof則常用來判斷物件是否為某個class 的實例。

3. in

如果我們要根據物件是否具有某個屬性來進行型別收窄,可以使用 in

//in範例:
interface Admin {
	name: string; 
	permissions: string[];
}

interface Steve {
	name: string; 
	points: number;
}

function printAccount(person: Admin | Steve) {
  if ("permissions" in person) {
    console.log(person.permissions);
  } else {
    console.log(person.points);
  }
}

4. 等值收窄(Equality Narrowing)

等值收窄能夠透過等比較運算來收窄型別範圍,常見的運算子有:

  • ===
  • !==
  • ==
  • !=
    也可以使用switch語法來判別喔!
//等值運算範例:
//情境1:(使用switch語法)
function getStatus(status: "success" | "error" | "loading") {
  switch (status) {
    case "success":
      console.log("成功!");
      break;
    case "error":
      console.log("錯誤");
      break;
    case "loading":
      console.log("載入中");
      break;
  }
}
//情境2:(協助不明確參數判定型別)
function compare(a: string | number, b: string) {
  if (a === b) { //當a等值於b時,a的型別會被認為與b相同,皆為string
    console.log(a.toLowerCase());
  }
}

//null也能夠使用:
function printName(name: string | null) {
  if (name !== null) {
    console.log(name.toUpperCase());
  }
}

Type Guard

上面介紹的typeofinstanceofin等方式,都可以作為TypeScript判斷型別的依據。而除了這些內建的判斷方式外,我們也可以自己建立Type Guard

//自訂Type Guard範例:
type Dog= {
  name: string;
  bark: () => void;
};

type Cat = {
  name: string;
  meow: () => void;
};

function isDog(animal: Dog | Cat): animal is Dog {
  return "bark" in animal;
}

function makeSound(animal: Dog | Cat) {
  if (isDog(animal)) {
    animal.bark();
  } else {
    animal.meow();
  }
}

小結

今天介紹了型別收窄的觀念和相關的語法,我覺得在邏輯判別很實用之外,也更了解TS是如何判斷變數是什麼型別的,今天就先到這邊啦!各位我們明天見囉!


上一篇
[Day-12]型別斷言(Type Assertion)
下一篇
[Day-14]Enum列舉
系列文
從零開始學習TypeScript:菜鳥的入門介紹與概覽22
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言